<?php

namespace App\Http\Controllers\Goods;

use App\Models\Goods\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    public function index()
    {
        return view('web.goods.index');
    }

    public function query(Request $request)
    {
        $code_type = $request->get('code_type');
        if(!empty($code_type)){
            $data = Goods::with(['goodsType','goodsRecord'=> function ($query) {
                $query->select('goods_id','number');
            }])->where('code_type',$code_type)->orderBy('id','desc')->get()->toArray();
        }else{
            $data = Goods::with(['goodsType','goodsRecord'=>function ($query) {
                $query->select('goods_id','number');
            }])->orderBy('id','desc')->get()->toArray();
        }
        foreach ($data as &$item) {
            if(!empty($item['goods_record'])){
                $item['goods_record'] = array_sum(array_column($item['goods_record'],'number'));
            }else{
                $item['goods_record'] = 0;
            }
            if(!empty($item['goods_type'])){
                $item['goods_type'] = $item['goods_type']['name'] ;
            }else{
                $item['goods_type'] = '';
            }
        }
        return view('web.goods.list',compact('data'));
    }

    public function buy(Request $request)
    {
        $info = $request->get('goods_id','number');
//        购买前验证当前用户余额
        $data = ['code'=>0,'result'=>'/web/resources/all'];
        return $data ;
    }
}
